﻿using System.ComponentModel;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Altairis.Web.UI.WebControls {

    /// <summary>
    /// Validator checking if required user name exists or not exists.
    /// </summary>
    [ToolboxData("<{0}:UserNameValidator runat=server></{0}:UserNameValidator>")]
    public class UserNameValidator : BaseValidator {

        [Category("Behavior")]
        public UserNameValidator() {
            this.Mode = UserNameValidatorMode.MustNotExist;
        }

        /// <summary>
        /// Defines if validator requires that user with given name exists or not exists.
        /// </summary>
        [Description("Defines if validator requires that user with given name exists or not exists.")]
        [DefaultValue(UserNameValidatorMode.MustNotExist)]
        public UserNameValidatorMode Mode {
            get { return (UserNameValidatorMode)this.ViewState["Mode"]; }
            set { this.ViewState["Mode"] = value; }
        }

        protected override bool EvaluateIsValid() {
            string userName = this.GetControlValidationValue(this.ControlToValidate);
            if (string.IsNullOrEmpty(userName)) return true; // empty input
            MembershipUser u = Membership.GetUser(userName, false);

            if (this.Mode == UserNameValidatorMode.MustExist) return u != null;
            else return u == null;
        }
    }
}